<template>
  <div class="pickScanHeader">
    <div class="common-loading" v-show="loadings.form">
      <van-loading type="spinner" color="#ed6d00" />
    </div>
    <van-nav-bar title="拣货扫描" left-text="返回" right-text="详情" @click-right="onClickDetail" @click-left="onClickBack"></van-nav-bar>
    <!-- form 表单布局 -->
    <van-form :show-error-message="false" class="common-form">
      <van-field
        ref="pickTaskCode"
        id="pickTaskCode"
        v-model="form.pickTaskCode"
        label="拣货任务号"
        @clear="clearTaskCode"
        @focus="disableKeyboard('pickTaskCode')"
        @click="disableKeyboard('pickTaskCode')"
        @keydown.enter.native="!pdaScanData.data ? receiveTaskCode() : ''"
        :readonly="readOnlys.pickTaskCode"
        clearable
        placeholder="请扫描拣货任务号"
        :rules="[{required: true, message: '请扫描拣货任务号'}]"
      />
      <div class="pick-info" v-if="form.pickTaskId">
        <div class="pick-info__title">
          {{ pickTitle }}
        </div>
        <van-cell>
          <div slot="title">
            <van-field readonly clickable placeholder="选择库位" v-model="form.locationCode" @click="changeLocationCode(true)" />
            <van-popup v-model="showPopups.locationNo" round position="bottom">
              <van-picker
                show-toolbar
                ref="locationRef"
                :columns="localtionList"
                value-key="locationCode"
                :default-index="defultInds.locationNo"
                @cancel="changeLocationCode(false)"
                @confirm="locationNoConfirm"
              />
            </van-popup>
          </div>
          {{ form.skuDesc }}
        </van-cell>
        <van-cell>
          <div slot="title">
            <van-field readonly clickable placeholder="选择sku" v-model="form.sku" @click="changeSku(true)" />
            <van-popup v-model="showPopups.sku" round position="bottom">
              <van-picker
                ref="skuRef"
                show-toolbar
                :columns="skuList"
                value-key="sku"
                :default-index="defultInds.sku"
                @cancel="changeSku(false)"
                @confirm="skuConfirm"
              />
            </van-popup>
          </div>
          {{ form.barCode }}
        </van-cell>
      </div>
      <van-field
        ref="cartonNo"
        id="cartonNo"
        label="拣货箱号"
        placeholder="请扫描拣货箱号"
        v-model="form.cartonNo"
        :disabled="!!isEditCartonNo"
        @keydown.enter.native="!pdaScanData.data ? handleCartonNo() : ''"
        @focus="disableKeyboard('cartonNo')"
        @click="disableKeyboard('cartonNo')"
        :readonly="readOnlys.cartonNo"
        clearable
        :rules="[{required: true, message: '请扫描拣货箱号'}]"
      />
      <van-field
        ref="locationNoCodeNum"
        id="locationNoCodeNum"
        v-model="form.locationNoCodeNum"
        label="库位"
        placeholder="请扫描库位"
        @keydown.enter.native="!pdaScanData.data ? handleLocationNo() : ''"
        @focus="disableKeyboard('locationNoCodeNum')"
        @click="disableKeyboard('locationNoCodeNum')"
        :readonly="readOnlys.locationNoCodeNum"
        clearable
        :rules="[{required: true, message: '请扫描库位'}]"
      />
      <van-field
        ref="scanValue"
        id="scanValue"
        v-model="form.scanValue"
        :label="form.scanType === 'qr_code' ? '商品唯一码' : '商品条码'"
        :placeholder="form.scanType === 'qr_code' ? '请扫描商品唯一码' : '请扫描商品条码'"
        @keydown.enter.native="!pdaScanData.data ? handleScanValue() : ''"
        @focus="disableKeyboard('scanValue')"
        @click="disableKeyboard('scanValue')"
        :readonly="readOnlys.scanValue"
        clearable
        :rules="[{required: true, message: form.scanType === 'qr_code' ? '请扫描商品唯一码' : '请扫描商品条码'}]"
      />
      <van-row type="flex" class="pick-info__num">
        <van-col span="8"><van-cell title="需拣" :value="form.sumAllocQty"/></van-col>
        <van-col span="8"><van-cell title="已拣" :value="form.sumPickedQty" /> </van-col>
        <van-col span="8"><van-cell title="差异" :value="diffNumber" /> </van-col>
      </van-row>
    </van-form>
    <!-- 表格布局 -->
    <van-cell-group>
      <van-row>
        <van-row type="flex">
          <van-col span="7">
            <van-cell-group>
              <van-cell title="商品" />
            </van-cell-group>
          </van-col>
          <van-col span="7">
            <van-cell-group>
              <van-cell title="库位" />
            </van-cell-group>
          </van-col>
          <van-col span="4">
            <van-cell-group>
              <van-cell title="数量" />
            </van-cell-group>
          </van-col>
          <van-col span="6">
            <van-cell-group>
              <van-cell title="拣货时间" />
            </van-cell-group>
          </van-col>
        </van-row>
      </van-row>
      <van-row type="flex" justify="center" align="center" class="pick-list" v-for="(item, index) in pickedList" :key="index">
        <van-col span="7">
          <span>{{ item.sku }}</span>
        </van-col>
        <van-col span="7">
          <span>{{ item.locationCode }}</span>
        </van-col>
        <van-col span="4" class="text-center">
          <span>{{ item.pickQty }}</span>
        </van-col>
        <van-col span="6" class="text-center">
          <span>{{ formatNumberToDateTime(item.createdDate) }}</span>
        </van-col>
      </van-row>
    </van-cell-group>
    <audio ref="successAudio" :src="successSource"></audio>
    <audio ref="errorAudio" :src="errorSource"></audio>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import {receivePickTaskWithTaskCode, insertPickingLog, formatNumberToDateTime} from "@/api/pickScan/pickTask";
const defaultForm = {
  pickTaskId: "",
  pickTaskCode: "",
  bussinessType: "",
  orderType: "",
  cartonNo: "",
  cartonId: "",
  brandCode: "",
  sku: "",
  sumAllocQty: 0,
  sumPickedQty: 0,
  skuDesc: "",
  barCode: "", // 69码
  locationId: "",
  locationCode: "", // 选择的库位
  locationNoCodeNum: "", // 输入的库位
  scanType: "",
  scanValue: ""
};
export default {
  name: "pickScanHeaderIndex",
  computed: {
    ...mapGetters("scanner", ["pdaScanData"]),
    ...mapGetters("user", ["userData"]),
    ...mapGetters("app", ["getPickScanInfo"]),
    storerId() {
      return this.$root.storerWarehouseBrand.storerId;
      // return "1363766180114636802";
    },
    warehouseId() {
      return this.$root.storerWarehouseBrand.warehouseId;
      // return "1389403318315229185";
    },
    brandId() {
      return this.$root.storerWarehouseBrand.brandId;
      // return "1380787545573191682";
    },
    diffNumber() {
      return Number(this.form.sumAllocQty) - Number(this.form.sumPickedQty);
    },
    isValueEmpty() {
      let arry = ["pickTaskCode", "cartonNo", "locationNoCodeNum", "scanValue"];
      let flag = true;
      for (let i = 0; i < arry.length; i++) {
        if (!this.form[arry[i]]) {
          flag = false;
          break;
        }
      }
      return flag;
    }
  },
  watch: {
    pdaScanData: {
      handler(data) {
        let input = document.activeElement.id;
        if (input == "pickTaskCode") {
          this.form.pickTaskCode = data.data;
          this.receiveTaskCode();
        } else if (input == "cartonNo") {
          this.form.cartonNo = data.data;
          this.handleCartonNo();
        } else if (input == "locationNoCodeNum") {
          this.form.locationNoCodeNum = data.data;
          this.handleLocationNo();
        } else if (input == "scanValue") {
          this.form.scanValue = data.data;
          this.handleScanValue();
        }
      },
      deep: true
    }
  },
  data() {
    return {
      errorSource: require("@/assets/sound/error.mp3"),
      successSource: require("@/assets/sound/success.mp3"),
      form: {...defaultForm},
      defultInds: {
        locationNo: 0,
        sku: 0
      },
      showPopups: {
        locationNo: false,
        sku: false
      },
      readOnlys: {
        pickTaskCode: false,
        cartonNo: false,
        locationNoCodeNum: false,
        scanValue: false
      },
      isEditCartonNo: true,
      skuList: [],
      localtionList: [],
      taskResponse: {},
      pickTitle: "",
      pickedList: [],
      picktaskInfor: {},
      loadings: {
        form: false
      }
    };
  },
  mounted() {
    if (this.getPickScanInfo.pickTaskCode) {
      this.form.pickTaskCode = this.getPickScanInfo.pickTaskCode;
      this.receiveTaskCode();
    }
    this.check();
  },
  methods: {
    formatNumberToDateTime(createdDate) {
      return formatNumberToDateTime(createdDate);
    },
    // 禁用键盘
    disableKeyboard(name) {
      this.readOnlys[name] = true;
      setTimeout(() => {
        this.readOnlys[name] = false;
      }, 200);
    },
    handleCartonNo() {
      if (!this.form.pickTaskId) {
        this.form.cartonNo = "";
        this.$nextTick(() => {
          this.$refs["pickTaskCode"].focus();
        });
        return;
      }
      this.$nextTick(() => {
        this.$refs["locationNoCodeNum"].focus();
      });
    },
    // 输入库位后触发的事件
    handleLocationNo() {
      if (!this.form.pickTaskId) {
        this.form.locationNoCodeNum = "";
        this.$nextTick(() => {
          this.$refs.pickTaskCode.focus();
        });
        return;
      }
      if (this.form.locationNoCodeNum) {
        // 如果扫描的库位 跟 当前选择的库位不一致 则 清空扫描库位值
        if (this.form.locationNoCodeNum !== this.form.locationCode) {
          this.form.locationNoCodeNum = "";
          this.$refs["locationNoCodeNum"].focus();
          this.playErrorSound();
          return;
        }
        this.check();
      }
    },
    // 取消库位选择
    changeLocationCode(flag) {
      this.showPopups.locationNo = flag;
      setTimeout(() => {
        this.setLocationDefaultIndex();
      }, 200);
    },
    setLocationDefaultIndex() {
      this.defultInds.locationNo = this.localtionList.findIndex(item => item.locationCode === this.form.locationCode);
      this.defultInds.locationNo > -1 && this.$refs.locationRef && this.$refs.locationRef.setColumnIndex(this.defultInds.locationNo);
    },
    // 确定库位选择
    locationNoConfirm(value) {
      this.form.locationId = value.locationId;
      this.form.locationCode = value.locationCode;
      this.showPopups.locationNo = false;
      this.receiveTaskCode(true, this.form.locationId, this.form.locationCode);
    },
    skuConfirm(value) {
      this.form.sku = value.sku;
      this.form.skuDesc = value.skuDesc;
      this.form.barCode = value.barCode;
      this.form.sumAllocQty = value.sumAllocQty;
      this.form.sumPickedQty = value.sumPickedQty;
      this.showPopups.sku = false;
    },
    changeSku(flag) {
      this.showPopups.sku = flag;
      setTimeout(() => {
        this.setSkuDefaultIndex();
      }, 200);
    },
    setSkuDefaultIndex() {
      this.defultInds.sku = this.skuList.findIndex(item => item.sku === this.form.sku);
      this.defultInds.sku > -1 && this.$refs.skuRef && this.$refs.skuRef.setColumnIndex(this.defultInds.sku);
    },
    // 获取任务号
    receiveTaskCode(flag, locationId, locationCode, sku, isUpdatePicked) {
      // 拣货任务号为空
      if (!this.form.pickTaskCode) {
        this.clearTaskCode();
        this.check();
        return;
      }
      let params = {
        storerId: this.storerId,
        warehouseId: this.warehouseId,
        brandId: this.brandId,
        pickTaskCode: this.form.pickTaskCode,
        userCode: this.userData.sysUserLoginName
      };
      if (flag) {
        params.pickTaskId = this.form.pickTaskId;
        params.locationId = locationId || this.form.locationId;
        params.locationCode = locationCode || this.form.locationCode;
      }
      this.loadings.form = true;
      receivePickTaskWithTaskCode(params)
        .then(response => {
          this.loadings.form = false;
          if (response.data.status) {
            // 成功操作
            let taskResponse = response.data.data;
            this.skuList = taskResponse.picktasklocationsku;
            if (!flag) {
              this.localtionList = taskResponse.picktasklocation;
              this.picktaskInfor = taskResponse.picktaskInfor[0];
              let picktaskInfor = taskResponse.picktaskInfor[0];
              this.form.scanType = taskResponse.scanType;
              this.form.pickTaskId = picktaskInfor.id;
              this.pickTitle = `${picktaskInfor.pickTaskCode} - ${picktaskInfor.bussinessType}${
                picktaskInfor.bussinessType === "B2B" ? "" : " - " + picktaskInfor.orderType
              }`;
              this.form.cartonNo = picktaskInfor.cartonNo || this.getPickScanInfo.cartonNo;
              this.isEditCartonNo = this.form.cartonNo;
              this.form.sku = taskResponse.sku;
              this.pickedList = taskResponse["pickedList"] || [];
            }
            this.form.locationId = locationId || taskResponse.locationId;
            this.form.locationCode = locationCode || taskResponse.locationCode;
            if (locationCode) {
              this.form.locationNoCodeNum = this.form.locationNoCodeNum === locationCode ? locationCode : "";
            } else {
              this.form.locationNoCodeNum = this.getPickScanInfo.locationNoCodeNum || "";
            }
            this.form.sku = sku ? sku : this.form.sku;
            let currentSkuList = taskResponse.picktasklocationsku.filter(item => item.sku == this.form.sku);
            let currentSku = currentSkuList.length > 0 ? currentSkuList : taskResponse.picktasklocationsku;
            currentSku = currentSku.length > 0 && currentSku[0];
            this.form.sku = currentSku.sku;
            this.form.barCode = currentSku.barCode;
            this.form.skuDesc = currentSku.skuDesc;
            this.form.sumAllocQty = currentSku.sumAllocQty;
            if ((flag && !isUpdatePicked) || !flag) {
              this.form.sumPickedQty = currentSku.sumPickedQty;
            }
            if (this.getPickScanInfo.pickTaskCode) {
              this.clearPickInfo();
            }
            this.check();
          } else {
            this.form.pickTaskCode = "";
            this.$toast.fail(response.data.message);
          }
        })
        .catch(() => {
          this.loadings.form = false;
          this.form.pickTaskCode = "";
          this.$toast.fail("请求出错！");
        });
    },
    clearTaskCode() {
      this.form = {...defaultForm};
      this.$refs["locationNoCodeNum"].resetValidation();
      this.$refs["scanValue"].resetValidation();
      if (!(!!this.form.cartonNo || !this.form.pickTaskId)) {
        this.$refs["cartonNo"].resetValidation();
      }
      this.skuList = [];
      this.localtionList = [];
      this.taskResponse = {};
      this.pickTitle = "";
      this.pickedList = [];
      this.picktaskInfor = {};
      this.check();
    },
    // 播放成功提示声
    playSuccessSound() {
      this.$refs["successAudio"].play();
    },
    // 播放错误提示声
    playErrorSound() {
      this.$refs["errorAudio"].play();
    },
    // 检验箱号 库位 条码那个字段值为空，若为空，则获取焦点
    check() {
      let arry = ["pickTaskCode", "cartonNo", "locationNoCodeNum", "scanValue"];
      let flag = true;
      arry.forEach(item => {
        if (flag && !this.form[item]) {
          this.$nextTick(() => {
            this.$refs[item] && this.$refs[item].focus();
          });
          flag = false;
        }
      });
    },

    handleScanValue() {
      if (!this.form.pickTaskId) {
        this.form.scanValue = "";
        this.$nextTick(() => {
          this.$refs.pickTaskCode.focus();
        });
        return;
      }
      if (!this.isValueEmpty) {
        this.form.scanValue = "";
        this.check();
        return;
      }
      // 判断库位不止指定库位
      if (this.form.locationNoCodeNum !== this.form.locationCode) {
        this.playErrorSound();
        this.form.locationNoCodeNum = "";
        this.form.scanValue = "";
        this.$toast.fail("当前库位不是指定库位,请重新输入库位！");
        this.check();
        return;
      }
      if (this.diffNumber <= 0) {
        this.playErrorSound();
        this.$toast.fail("该SKU已全扫描，请选择下一个未完成扫描的SKU！");
        this.check();
        this.form.scanValue = "";
        return;
      }
      let params = {
        storerId: this.storerId, // 货主id
        warehouseId: this.warehouseId, // 仓库Id
        brandId: this.brandId, // 品牌Id
        userCode: this.userData.sysUserLoginName, // 当前用户
        pickTaskId: this.form.pickTaskId, // 任务id
        pickTaskCode: this.form.pickTaskCode, // 任务号
        locationId: this.form.locationId, // 库位id
        locationCode: this.form.locationCode, // 库位编码
        sku: this.form.sku, // 商品编码
        scanType: this.form.scanType, // 扫描类型
        scanValue: this.form.scanValue, // 扫描值
        scanQty: this.form.scanQty, // 操作数量
        cartonNo: this.form.cartonNo // 拣货箱号
      };
      this.loadings.form = true;
      insertPickingLog(params)
        .then(response => {
          this.form.scanValue = "";
          this.loadings.form = false;
          if (response.data.status) {
            this.playSuccessSound();
            let res = response.data.data;
            // 任务关闭
            if (res.isClose) {
              this.pickedList = [];
              this.form.sumPickedQty = 0;
              this.form.sumAllocQty = 0;
              this.closeTaskDialog(response.data.message);
              return;
            } else {
              this.pickedList = response.data.data.pickedList || [];
              this.form.sumPickedQty = response.data.data.pickedQty;
              this.receiveTaskCode(true, res.locationId, res.locationCode, res.sku, res.locationId === this.form.locationId ? true : false);
            }
            // 获取信息
          } else {
            this.playErrorSound();
            this.$toast.fail(response.data.message);
          }
        })
        .catch(() => {
          this.form.scanValue = "";
          this.loadings.form = false;
          this.playErrorSound();
          this.$toast.fail("请求出错！");
        });
    },
    closeTaskDialog(message) {
      this.$dialog
        .confirm({
          message: message,
          confirmButtonText: "查看任务详情",
          cancelButtonText: "关闭"
        })
        .then(() => {
          this.clearPickInfo();
          this.$router.push({
            name: "b2cPickScanTaskDetail",
            query: {
              pickTaskId: this.form.pickTaskId
            }
          });
        })
        .catch(() => {
          this.clearTaskCode();
        });
    },
    clearPickInfo(info) {
      let params = {
        pickTaskCode: "",
        cartonNo: "",
        locationNoCodeNum: ""
      };
      this.$store.commit("app/setPickInfo", info ? info : params);
    },
    onClickDetail() {
      if (this.form.pickTaskId == "") {
        this.$toast.fail("请先去领取任务！");
        this.check();
      } else {
        let params = {
          pickTaskCode: this.form.pickTaskCode,
          cartonNo: this.form.cartonNo,
          locationNoCodeNum: this.form.locationNoCodeNum
        };
        this.clearPickInfo(params);
        this.$router.push({
          name: "b2cPickScanTaskDetail",
          query: {
            pickTaskId: this.form.pickTaskId
          }
        });
      }
    },
    onClickBack() {
      this.clearPickInfo();
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="less" scoped>
.pickScanHeader {
  .pick-info {
    border-bottom: 1px dotted #ebedf0;
    /deep/ .van-cell {
      padding: 4px 16px;
      &::after {
        border-bottom: 0;
      }
    }
    &__title {
      font-weight: 600;
      padding: 4px 16px;
      font-size: 14px;
    }
    &__num {
      /deep/ .van-cell__value {
        color: #333;
        text-align: center;
        color: #ed6d00;
      }
    }
    /deep/ .van-field {
      padding: 0;
      .van-field__control {
        text-align: left;
      }
      &::after {
        border-bottom: 0;
      }
    }
  }
  .pick-list {
    /deep/ .van-col {
      font-size: 14px;
      padding: 8px 4px;
      span {
        word-break: break-all;
        word-break: break-word;
      }
    }
    .text-center {
      text-align: center;
    }
  }
}
</style>
